<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <ul>
      <li><a href="/a">a</a></li>
      <li><a href="/b">b</a></li>
      <li><a href="/c">c</a></li>
    </ul>
    <div id="view"></div>

    <script>
      var view = null;
      // 页面加载完不会触发 hashchange，这里主动触发一次 hashchange 事件,该事件快于onLoad,所以需要在这里操作
      window.addEventListener("DOMContentLoaded", function() {
        view = document.querySelector("#view");
        document.querySelectorAll("a[href]").forEach((e) =>
          e.addEventListener("click", function(_e) {
            _e.preventDefault();
            console.log(e.getAttribute("href"));
            history.pushState(null, "", e.getAttribute("href"));
            viewChange();
          })
        );

        viewChange();
      });
      // 监听路由变化
      // window.addEventListener("popstate", viewChange);

      // 渲染视图
      function viewChange() {
        console.log(location.pathname);
        switch (location.pathname) {
          case "/b":
            view.innerHTML = "b";
            break;
          case "/c":
            view.innerHTML = "c";
            break;
          default:
            view.innerHTML = "a";
            break;
        }
      }
    </script>
  </body>
</html>
